import subprocess

import re

import subprocess

import time

def replace_symbols(text):
    if text is None:
        return None
    # 保留：字母、数字、空格、中文，其余替换为 .
    return re.sub(r'[^\u4e00-\u9fa5a-zA-Z0-9 ]', '.', text)

def get_iina_window_title():
    script = '''
    tell application "System Events"
        set iinaProcesses to every process whose name is "IINA"
        if (count of iinaProcesses) > 0 then
            repeat with p in iinaProcesses
                set windowCount to count windows of p
                if windowCount > 0 then
                    repeat with w in windows of p
                        set winName to name of w
                        if winName is not missing value and winName does not start with "Preferences" then
                            return winName
                        end if
                    end repeat
                end if
            end repeat
        end if
        return ""
    end tell
    '''

    result = subprocess.run(['osascript', '-e', script], capture_output=True, text=True)
    title = result.stdout.strip()
    res = title if title else None
    res = replace_symbols(title)
    return res

# # 调用函数并打印结果
# title = get_iina_window_title()
# if title:
#     print("IINA 正在播放的视频标题是：", title)
# else:
#     print("未找到 IINA 的播放窗口")




# 获取正在打开的最前的程序
def get_frontmost_app():
    # 使用AppleScript获取最前面的应用程序名称
    script = '''
        tell application "System Events"
            name of first application process whose frontmost is true
        end tell
    '''
    # 使用subprocess运行osascript命令执行AppleScript
    result = subprocess.run(['osascript', '-e', script], capture_output=True, text=True)
    
    if result.returncode == 0:  # 如果脚本成功运行
        app_name = result.stdout.strip()  # 去除多余的空白字符
        return app_name
    else:
        # print("无法获取当前最前的应用程序:", result.stderr)
        return None

# if __name__ == '__main__':

#     # time.sleep(3)

#     app = get_frontmost_app()
#     if app:
#         print(f"当前最前面的应用程序是: {app}")